Q: I have spent a while trying to figure out how to play sounds
in Java. Sun has some audio classes, but they are unsupported and not
very flexible. Is there any other way to play sounds in Java?
A: Yes. Using QuickTime for Java, you can easily play sounds
stored in a variety of formats. The following application example simply
plays a local sound file:
import quicktime.QTSession;
import quicktime.app.QTFactory;
import quicktime.app.players.QTPlayer;
public class Application
{
static QTPlayer player; // static so it is not garbage collected
static public void main (String[ ] args) {
try {
QTSession.open();
String soundLocation = QTFactory.findAbsolutePath(
"sin440.aif" ).getPath();
//this call works with a file://, http://, rtsp:// located movies
player = (QTPlayer)QTFactory.makeDrawable (
"file://" + soundLocation);
player.startTasking();
player.setRate(1);
}
catch (Exception e) {
e.printStackTrace();
QTSession.close();
}
}
}
|
In this example, we initialize QuickTime by calling the static
open( ) method from the QTSession class. It is important to call
QTSession.open( ) before making any QuickTime for Java calls and QTSession.close( )
before the applet or application terminates.
Next, we load the file by using the QTFactory utility class
to generate a URL from a local file path. This location is simply a string. If you
are using an applet, you may wish to format the string to specify a
file from an http server (this also works with applications). Next, we
create a drawable object from the string. This may seem counter-intuitive
since we are dealing with a sound and not a movie. This is because QuickTime
treats sound and media files, as well as other time-based formats, in a
consistent manner. By making a drawable object, we are preparing the file to
be presented by the QTPlayer . This is also important, because your application may
want to display a controller for controlling the playback of the sound
file. In this case, you would create a QTCanvas and add the QTPlayer to
it.
Then, we call the startTasking( ) of the QTPlayer inherited
from the Taskable class. This creates a task that is responsible for
handling the periodic data. Setting the rate of the movie to 1 plays the movie
(or sound in this case). The rate is a floating point value that
specifies how to play the media. The value "1" means normal speed, "0.5"
denotes half speed, and "-1" denotes full speed backwards. Setting the rate to "0"
stops playback.
We chose this methodology to play sound files because it is fairly
robust, allows files to be located on disk, on the web, or streamed, and
supports a variety of sound file formats including AIFF, wav, au, and MP3.
QuickTime for Java is an excellent way to have rich media support if you are targeting your application for
deployment on Windows and Macintosh. For more information, see the
QuickTime for Java Overview.
[Oct 25 1999]
|